from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db.models import Q
from django.urls import reverse
from app.models import UserProfile
from utils.choices import *

search_fields = [
    'gender', 'age', 'nickname', 'birthdate', 'marital_status', 'height',
    'weight', 'education', 'monthly_income', 'occupation', 'housing_status',
    'car_status', 'marriage_expectation', 'self_introduction', 'parental_involvement',
    'wechat', 'wechat_QR', 'qq', 'parent_status', 'live_with_parents',
    'smoking_status', 'marriage_form', 'children_status', 'pets', 'hobbies',
    'blood_type', 'ethnicity', 'alma_mater', 'employer_type', 'employer',
    'property_location'
]


def search_user(user_list, search_params):
    # 全部查询条件
    if search_params['all_search']:
        queries = [Q(**{f"{field}__icontains": search_params['all_search']}) for field in search_fields]
        search_query = Q()
        for item in queries:
            search_query |= item
        user_list = user_list.filter(search_query)
    # 应用年龄范围过滤条件
    if search_params['nickname']:
        user_list = user_list.filter(nickname__contains=search_params['nickname'])  # 模糊搜索

    # 应用年龄范围过滤条件
    if search_params['age_range']:
        min_age, max_age = map(int, search_params['age_range'].split('-'))
        user_list = user_list.filter(age__gte=min_age, age__lte=max_age)  # 范围搜索

    # 应用身高范围过滤条件
    if search_params['height_range']:
        min_height, max_height = map(int, search_params['height_range'].split('-'))
        user_list = user_list.filter(height__gte=min_height, height__lte=max_height)  # 范围搜索

    # 应用体重范围过滤条件
    if search_params['weight_range']:
        min_weight, max_weight = map(int, search_params['weight_range'].split('-'))
        user_list = user_list.filter(weight__gte=min_weight, weight__lte=max_weight)  # 范围搜索

    # 应用工作地区过滤条件 省
    if search_params['work_province']:
        user_list = user_list.filter(work_province__contains=search_params['work_province'])  # 模糊搜索

    # 应用工作地区过滤条件 市
    if search_params['work_city']:
        user_list = user_list.filter(work_city__contains=search_params['work_city'])  # 模糊搜索

    # 应用工作地区过滤条件 区
    if search_params['work_area']:
        user_list = user_list.filter(work_area__contains=search_params['work_area'])  # 模糊搜索

    # 应用户籍地区过滤条件 省
    if search_params['my_province']:
        user_list = user_list.filter(my_province__contains=search_params['my_province'])  # 模糊搜索

    # 应用户籍地区过滤条件 市
    if search_params['my_city']:
        user_list = user_list.filter(my_city__contains=search_params['my_city'])  # 模糊搜索

    # 应用户籍地区过滤条件 区
    if search_params['my_area']:
        user_list = user_list.filter(my_area__contains=search_params['my_area'])  # 模糊搜索

    # 应用婚姻状况过滤条件
    if search_params['marital_status']:
        user_list = user_list.filter(marital_status__in=search_params['marital_status'])  # 多条件

    # 应用民族过滤条件
    if search_params['ethnicity']:
        user_list = user_list.filter(ethnicity__in=search_params['ethnicity'])  # 多条件

    # 应用子女情况过滤条件
    if search_params['children_status']:
        user_list = user_list.filter(children_status__in=search_params['children_status'])  # 多条件

    # 应用最低学历过滤条件（多选）
    if search_params['minimum_education']:
        user_list = user_list.filter(education__in=search_params['minimum_education'])  # 多条件

    # 应用最低月收入过滤条件
    if search_params['minimum_income']:
        user_list = user_list.filter(monthly_income__in=search_params['minimum_income'])  # 多条件

    # 应用职业过滤条件
    if search_params['occupation']:
        user_list = user_list.filter(occupation__in=search_params['occupation'])  # 多条件

    # 应用住房情况过滤条件
    if search_params['housing_status']:
        user_list = user_list.filter(housing_status__in=search_params['housing_status'])  # 多条件

    # 应用购车情况过滤条件
    if search_params['car_status']:
        user_list = user_list.filter(car_status__in=search_params['car_status'])  # 多条件

    # 应用期望结婚时间过滤条件
    if search_params['marriage_timing']:
        user_list = user_list.filter(marriage_expectation__in=search_params['marriage_timing'])  # 多条件
    return user_list


def paginator_set(user_list, search_params):
    # 创建分页对象
    paginator = Paginator(user_list, search_params['page_size'])
    try:
        paginated_data = paginator.page(search_params['page'])
    except PageNotAnInteger:
        paginated_data = paginator.page(1)  # 如果页码不是整数，则显示第一页
    except EmptyPage:
        paginated_data = paginator.page(paginator.num_pages)  # 如果页码超出范围，则显示最后一页

    return paginated_data, paginator


def other_path(user_list, path, my_id):
    nearby = reverse('nearby')  # 附近'
    matching = reverse('matching')  # 匹配我
    recommend = reverse('recommend')  # 匹配我
    if path != recommend:
        my_list = UserProfile.objects.get(id=my_id)
        my_province = my_list.my_province  # 个人省份
        if path == nearby:
            user_list = user_list.filter(my_province__contains=my_province)
        if path == matching:
            user_list = matching_list(user_list, my_list)
        return user_list
    return user_list


def matching_list(user_list, my_list):
    search_params = {
        'age_range': my_list.age_range,  # 年龄范围
        'height_range': my_list.height_range,  # 身高范围
        'minimum_education': my_list.minimum_education,  # 最低学历
        'minimum_income': my_list.minimum_income,  # 最低收入
        'marriage_timing': my_list.marriage_timing,  # 结婚时间
        'desired_work_province': my_list.desired_work_province,  # 工作省
        'desired_work_city': my_list.desired_work_city,  # 工作市
        'desired_work_area': my_list.desired_work_area,  # 工作区
        'desired_housing_status': my_list.desired_housing_status,  # 房子要求
        'desired_marital_status': my_list.desired_marital_status,  # 婚姻状况
    }
    # 进行模糊查询
    user_list.filter(
        # 使用年龄范围进行筛选，假设age_range是'24-35'格式
        age__range=map(int, search_params['age_range'].split('-')),
        # 使用身高范围进行筛选，假设height_range是'154-176'格式
        height__range=map(int, search_params['height_range'].split('-')),
        # 使用最低学历进行筛选
        education__in=[k for k, v in EDUCATION_MAPPING.items() if
                       v >= EDUCATION_MAPPING[search_params['minimum_education']]],
        # 使用最低收入进行筛选
        monthly_income__in=[k for k, v in INCOME_MAPPING.items() if
                            v >= INCOME_MAPPING[search_params['minimum_income']]],
        # 使用结婚时间进行筛选
        marriage_timing__in=[k for k, v in MARRIAGE_TIMING_MAPPING.items() if
                             v <= MARRIAGE_TIMING_MAPPING[search_params['marriage_timing']]],
        # 使用工作省进行模糊匹配筛选
        work_province__icontains=search_params['desired_work_province'],
        # 使用工作市进行模糊匹配筛选
        work_city__icontains=search_params['desired_work_city'],
        # 使用工作区进行模糊匹配筛选
        work_area__icontains=search_params['desired_work_area'],
        # 使用住房状况进行模糊匹配筛选
        housing_status__icontains=search_params['desired_housing_status'],
        # 使用婚姻状况进行模糊匹配筛选
        marital_status__icontains=search_params['desired_marital_status']
    )
    return user_list


def data_object_list(data):
    list = [{
        'id': obj.id,
        'avatar': obj.avatar,
        'gender': obj.gender,
        'age': obj.age,
        'nickname': obj.nickname,
        'birthdate': obj.birthdate,
        'marital_status': obj.marital_status,
        'height': obj.height,
        'weight': obj.weight,
        'education': obj.education,
        'monthly_income': obj.monthly_income,
        'occupation': obj.occupation,
        'housing_status': obj.housing_status,
        'car_status': obj.car_status,
        'marriage_expectation': obj.marriage_expectation,
        'self_introduction': obj.self_introduction,
        'parental_involvement': obj.parental_involvement,
        'wechat': obj.wechat,
        'wechat_QR': obj.wechat_QR,
        'qq': obj.qq,
        'parent_status': obj.parent_status,
        'live_with_parents': obj.live_with_parents,
        'smoking_status': obj.smoking_status,
        'marriage_form': obj.marriage_form,
        'children_status': obj.children_status,
        'pets': obj.pets,
        'hobbies': obj.hobbies,
        'blood_type': obj.blood_type,
        'ethnicity': obj.ethnicity,
        'alma_mater': obj.alma_mater,
        'employer_type': obj.employer_type,
        'employer': obj.employer,
        'property_location': obj.property_location,
        'location': obj.location,
        'age_range': obj.age_range,
        'height_range': obj.height_range,
        'minimum_education': obj.minimum_education,
        'minimum_income': obj.minimum_income,
        'marriage_timing': obj.marriage_timing,
        'desired_housing_status': obj.desired_housing_status,
        'desired_marital_status': obj.desired_marital_status,
        'other_requirements': obj.other_requirements,
        'realName': obj.realName,
        'IDCode': obj.IDCode,
        'diplomaImage': obj.diplomaImage,
        'carImage': obj.carImage,
        'houseImage': obj.houseImage,
        'salaryImage': obj.salaryImage,
        'work_time': obj.work_time,
        'my_province': obj.my_province,
        'my_city': obj.my_city,
        'my_area': obj.my_area,
        'work_province': obj.work_province,
        'work_city': obj.work_city,
        'work_area': obj.work_area,
        'desired_work_province': obj.desired_work_province,
        'desired_work_city': obj.desired_work_city,
        'desired_work_area': obj.desired_work_area,
        'stick_status': obj.stick_status,
        'hot_status': obj.hot_status
    } for obj in data]
    return list
